﻿using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace TinyAsset
{
    public class AssetBundleLoader : BaseLoader<AssetBundleLoader>
    {
        string assetBundleName;

        AssetBundleCreateRequest assetBundleCreateRequest;
        AssetBundleLoader[] dependencies = _emptyArray;

        static AssetBundleLoader[] _emptyArray = new AssetBundleLoader[0];

        public AssetBundle assetBundle;

        public AssetBundleLoader(string bundleName, AssetBundleLoader[] depds):base(bundleName)
        {
            assetBundleName = bundleName;
            dependencies = depds == null ? _emptyArray : depds;
        }

        protected override void SyncLoadHandler()
        {
            if (assetBundle == null)
            {
                if (assetBundleCreateRequest != null)
                {
                    assetBundle = assetBundleCreateRequest.assetBundle;
                    assetBundleCreateRequest = null;
                }
                else
                    assetBundle = AssetBundle.LoadFromFile(AssetBundleUtility.GetAssetBundlePath(assetBundleName));
            }
            IsCompleted = true;
        }

        protected override void AsyncLoadHandler()
        {
            if (assetBundle == null)
            {
                Progress = 0f;

                bool LoadImmediately = true;
                foreach (var dependency in dependencies)
                {
                    Progress = Progress + dependency.Progress;
                    if (!dependency.IsDone)
                        LoadImmediately = false;
                }

                if (LoadImmediately)
                {
                    if (assetBundleCreateRequest == null)
                        assetBundleCreateRequest = AssetBundle.LoadFromFileAsync(AssetBundleUtility.GetAssetBundlePath(assetBundleName));
                    Progress = Progress + assetBundleCreateRequest.progress;
                    if (assetBundleCreateRequest.isDone)
                    {
                        assetBundle = assetBundleCreateRequest.assetBundle;
                        assetBundleCreateRequest = null;
                        IsCompleted = true;
                    }
                }

                Progress = Progress / (1 + dependencies.Length);
            }
        }

        public override void Unload()
        {
            if (assetBundle != null)
                assetBundle.Unload(true);
        }

        public override string ToString()
        {
            return string.Format("[{0}]-{1}", RefCount, assetBundleName);
        }
    }
}